<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\library\ExceptionHandle;
use think\Db;
/**
 *  抽奖管理
 *
 *  Author:  YSX
    Date:    2023-5-23
 */
class Draw extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
	//测试环境
	       // protected $url = 'http://pre.openapi.fulu.com/api/getway';
	       // protected $app_key = 'i4esv1l+76l/7NQCL3QudG90Fq+YgVfFGJAWgT+7qO1Bm9o/adG/1iwO2qXsAXNB';
	       // protected $AppSecret = '0a091b3aa4324435aab703142518a8f7';
	    //生产环境
	    // protected $url = 'http://openapi.fulu.com/api/getway';
	    // protected $app_key = 'dxuJ7/xGIXsAIFjWPdcryKTLKnLCxvoy39neoESfWWiLDYI/m8CoXl7b4/GBfgjn';
	    // protected $AppSecret = '39447679a5884dcaa92f4ffad47724e2';
	    // protected $noNeedLogin = '*';
	    // protected $noNeedRight = '*';
    public function _initialize()
    {
        parent::_initialize();
    }
    /*
     * 列表
    */
    public function prizeList()
    {
        // $params = $this->params;
		if (!$this->request->isPost()) {
			return $this->error('提交方式不正确');
		}
		$params = $this->request->post();
		$where['is_del'] = array('eq',1);
        $list = Db::name('prize')->where($where)
			  ->order('sort asc')
			  ->field('id,prize_name,type,image,add_time')
			  ->select(); 
		// halt($list);
		//首先判断此手机号是否已参与抽奖
		if ($list) {
			//判断手机号是否是订购业务的
			$conn = Db::connect(config('database.pajk'));
			$startTime = strtotime(date('Y-m'));
			$endTime = mktime(23,59,59,date('m',strtotime(date('Y-m')))+1,00);  //指定月份月末时间戳 
			$isFind = $conn->name('callback')->where('server_num',$params['mobile'])->where('add_time','between',[$startTime,$endTime])->find();
			//判断有没有订购年卡
			$paytime = strtotime("-1 year");
			$orderInfo = $conn->name('order')->where('mobile',$params['mobile'])->where('order_status',2)->where('pay_time','>',$paytime)->find();
			// halt($isFind);
			if($isFind || $orderInfo){
				// $data['draw_number'] = 1;
				// $startTime = strtotime(date('Y-m'));
				// $endTime = mktime(23,59,59,date('m',strtotime(date('Y-m')))+1,00);  //指定月份月末时间戳 
				$find = Db::name('winning')->where('mobile',$params['mobile'])->where('addtime','between',[$startTime,$endTime])->order('id desc')->find();
				if($find){
					if($find['type'] == 4){
						$data['draw_number'] = 1;
					}else{
						$data['draw_number'] = 0;
					}
				}else{
					$data['draw_number'] = 1;
				}
			}else{
				$data['draw_number'] = 0;
			}
			$data['list'] = $list;
			$this->success('获取成功', $data);
		}
		$this->error('请求失败');
    }

    /*
     * 抽奖
     */
    public function smokePrize()
    {
        if (!$this->request->isPost()) {
        	return $this->error('提交方式不正确');
        }
		$params = $this->request->post();
		$startTime = strtotime(date('Y-m'));
		$endTime = mktime(23,59,59,date('m',strtotime(date('Y-m')))+1,00);  //指定月份月末时间戳 
		//首先判断此手机号是否已参与抽奖
		$find = Db::name('winning')->where('mobile',$params['mobile'])->where('type','in','1,2,3')->where('addtime','between',[$startTime,$endTime])->find();
		// halt(Db::name('winning')->getLastSql());
		if($find){
			return $this->error(__('您本月已参与过此活动，请下月再来哦！'));
		}
		//判断手机号是否是订购业务的
		$conn = Db::connect(config('database.pajk'));
		$isFind = $conn->name('callback')->where('server_num',$params['mobile'])->where('add_time','between',[$startTime,$endTime])->find();
		//判断有没有订购年卡
		$paytime = strtotime("-1 year");
		$orderInfo = $conn->name('order')->where('mobile',$params['mobile'])->where('order_status',2)->where('pay_time','>',$paytime)->find();
		// halt($isFind);
		if($isFind || $orderInfo){
			// return $this->returnErr(__('非会员,需要先订购才能享受此活动'));
		}else{
			return $this->error(__('非会员,需要先订购才能享受此活动'));
		}
		$where['is_del'] = array('eq',1);
		$where['stock'] = array('gt',0);
		$list = Db::name('prize')->where($where)
			  ->field('id,prize_name,type,image,add_time,probability,sort,goods_code,stock')
			  ->order('probability asc')
			  ->select(); 
		// 概率重组
		$probability = 0;
		foreach ($list as $k => $v) {
		    $probability += $v['probability'];
		    $list[$k]['probability'] = $probability;
		}
		// 随机抽奖
		$rand = mt_rand(1, $probability);
		$result = [];
		foreach ($list as $k => $v) {
		    if ($k == 0) {
		        if ($rand > 0 && $rand <= $v['probability']) {
		            $result = $v;
		            break;
		        }
		    } else {
		        if ($rand > $list[$k-1]['probability'] && $rand <= $v['probability']) {
		            $result = $v;
		            break;
		        }
		    }
		}
		//把奖品保存到数据库
		$data['mobile'] = $params['mobile'];
		$data['prize_id'] = $result['id'];
		$data['image'] = $result['image'];
		$data['prize_name'] = $result['prize_name'];
		$data['type'] = $result['type'];
		$data['goods_code'] = $result['goods_code'];
		$data['rand'] = $rand;
		$data['addtime'] = time();
		$data['id'] = Db::name('winning')->insertGetId($data);
		//减少库存
		Db::name('prize')->where('id',$result['id'])->setDec('stock');
		$data['sort'] = $result['sort'];
		$this->success('恭喜你中奖了', $data);
    }
	//中奖之后填写信息
	public function saveInfo(){
		if (!$this->request->isPost()) {
			return $this->error('提交方式不正确');
		}
		$params = $this->request->post();
		//查找中奖信息
		$winningInfo = Db::name('winning')->where('id',$params['winning_id'])->find();
		// if($winningInfo['state'] == 1){
		// 	return $this->error('已经领取过奖品');
		// }
		if($winningInfo['type'] == 1){
			$data['recharge_mobile'] = $params['recharge_mobile'];
			$data['username'] = $params['username'];
			$data['address'] = $params['address'];
		}elseif($winningInfo['type'] == 2){
			//判断该用户是否已充值
			//如果是充值卡的话需要走充值接口(福禄的);
			$data['recharge_mobile'] = $params['recharge_mobile'];
			$rechargeInfo = $this->recharge($winningInfo,$params['recharge_mobile']);
			// halt($rechargeInfo);
			if($rechargeInfo['code'] == 0){
				//充值成功
				$data['state'] = 1;
				$data['deliver_time'] = time();
			}else{
				return $this->error($rechargeInfo['message'].',请联系客服解决');
			}
		}
		//修改数据库
		$result = Db::name('winning')->where('id',$params['winning_id'])->update($data);
		if($result){
			$this->success('保存信息成功');
		}else{
			$this->error(__('保存失败'));
		}
	}
	//中奖记录
	public function prizeRecord(){
		if (!$this->request->isPost()) {
			return $this->error('提交方式不正确');
		}
		$params = $this->request->post();
		//首先判断此手机号是否已参与抽奖
		$info = Db::name('winning')->where('mobile',$params['mobile'])->where('type','in','1,2')->select();
		$this->success('中奖记录',$info);
	}
	//查找用户领取了那些权益
	public function myEquity(){
		$params = $this->request->post();
		// $user_id = $this->auth->id;
		// $mobile = $this->auth->mobile;
		// $begin_time = strtotime(date('Y-m'));        //指定月份的开始时间戳
		// $end_time = mktime(23,59,59,date('m',strtotime(date('Y-m')))+1,00);  //指定月份月末时间戳 ; 
		//判断手机号是否是订购业务的
		$conn = Db::connect(config('database.pajk'));
		//查找别墅数据
		$goodsOrder = $conn->name('goods_order')->where('mobile',$params['mobile'])->select();
		foreach($goodsOrder as $key => $value){
			$goodsOrder[$key]['state'] = 1;
		}
		//查找投保数据
		$insureOrder = $conn->name('insure_order')->where('mobile',$params['mobile'])->select();
		foreach($insureOrder as $key => $value){
			$insureOrder[$key]['state'] = 2;
		}
		//中奖信息数据
		$prize = Db::name('winning')->where('mobile',$params['mobile'])->where('type','in','1,2')->select();
		foreach($prize as $key => $value){
			$prize[$key]['state'] = 3;
			$prize[$key]['add_time'] = $value['addtime'];
		}
		$a = array_merge($insureOrder,$goodsOrder);
	
		$data = array_merge($a,$prize);
		$c = array_column($data,'add_time');
		array_multisort($c,SORT_DESC,$data);
		// halt($b);
		// //查找免费问诊
		// $data['inquiryOrder'] = Db::name('inquiry')->where('mobile',$mobile)->where('add_time','between',[$begin_time,$end_time])->find();
		return $this->success(__('我的奖品'),$data);
	}
	//公共充值接口
	public function recharge($winningInfo,$mobile){
		$order_no = date('YmdHis', time()) . str_pad(5, 0, STR_PAD_LEFT) . rand(1000, 99999); //生成订单号
		$orderdata = [ //领取记录表
			'order_no' => $order_no,
			'mobile' => $mobile,
			'goods_id' => $winningInfo['prize_id'],
			'goods_name' => $winningInfo['prize_name'],
			'goods_code' => $winningInfo['goods_code'],
			'status' => 1,
			'create_time' => time(),
			'end_time' => 0
		];
		$res = Db::name('recharge_order')->insertGetId($orderdata);
		$config = config('fulu');
		$postData['app_key'] = $config['app_key'];
		$postData['method'] = 'fulu.order.direct.add';
		$postData['timestamp'] = date("Y-m-d H:i:s");
		$postData['version'] = '2.0';
		$postData['format'] = 'json';
		$postData['charset'] = 'utf-8';
		$postData['sign_type'] = 'md5';
		$postData['app_auth_token'] = '';

		$biz_content['customer_order_no'] = $order_no;
		// $biz_content['product_id'] = $category['code_marking']; //标识
		$biz_content['product_id'] = $winningInfo['goods_code'] ? : '10000586'; //标识
		$biz_content['buy_num'] = 1; //充值数量
		$biz_content['charge_account'] = $mobile; //账户
		$biz_content['charge_ip'] = $this->request->ip();
		$biz_content['charge_password'] = '';
		$biz_content['charge_game_name'] = '';
		$biz_content['charge_game_role'] = '';
		$biz_content['charge_game_region'] = '';
		$biz_content['charge_game_srv'] = '';
		$biz_content['charge_type'] = '';
		$biz_content['contact_tel'] = '';
		$biz_content['contact_qq'] = '';
		$postData['biz_content'] = json_encode($biz_content);
		$postData['sign'] = $this->getSign($postData);
		$result = json_decode(ExceptionHandle::curl_json($config['url'], json_encode($postData)), true);
		// halt($result);
		if ($result['code'] == 0) { //接口调用失败状态为充值未成功
			Db::name('recharge_order')->where('id',$res)->update(['status'=>2,'end_time'=>time()]);
			$data['code'] = 0;
			$data['message'] = '充值成功';
		} else {
			$data['code'] = $result['code'];
			$data['message'] = $result['message'];
		}
		return $data;
	}
	/**
	 * php签名方法
	 */
	public function getSign($Parameters)
	{
		$config = config('fulu');
		//签名步骤一：把字典json序列化
		$json = json_encode($Parameters, 320);
		//签名步骤二：转化为数组
		$jsonArr = preg_split('/(?<!^)(?!$)/u', $json);
		//签名步骤三：排序
		sort($jsonArr);
		//签名步骤四：转化为字符串
		$string = implode('', $jsonArr);
		//签名步骤五：在string后加入secret
		$string = $string . $config['AppSecret'];
		//签名步骤六：MD5加密
		$result_ = strtolower(md5($string));
		return $result_;
	}
}
